<?php
class Admin_BannerController extends Zend_Controller_Action {
	public function init() {
		/* Initialize action controller here */
	}
	public function indexAction() {
		$bannerDb = new Application_Model_DbTable_Banner();
		$banners = $bannerDb->fetchAll('del_flag = 0');
		$this->view->banners = $banners;
	}
	
	public function uploadAction(){
		if ($this->getRequest ()->isPost ()) {
			$errors = array ();
			$bannerDb = new Application_Model_DbTable_Banner();
				
			$adapter = new Zend_File_Transfer_Adapter_Http();
			$adapter->setDestination(APPLICATION_PATH . '/../public/imgs');
				
			$adapter->addValidator('Extension', true, 'jpg,png,gif');
			$adapter->addValidator('IsImage', false);
			$adapter->addValidator('Size', true, array(
					'min' => '5kB' ,
					'max' => '1MB' ,
					'bytestring' => false));
		
			$files = $adapter->getFileInfo();
			
				
			foreach ($files as $file => $info) {
				// file uploaded ?
				if (!$adapter->isUploaded($file)) {
					$errors[] = "Làm ơn chọn file upload";
				}else {
					
					// validators are ok ?
					if (!$adapter->isValid($file)) {
						$errors[] = "File không hợp lệ, kiểm tra lại kích thước ảnh và dung lượng file.";
					}
				}
			}
			if (count ( $errors ) == 0) {
				if (!$adapter->receive()){
					$errors = $adapter->getMessages();
				}
				$filepath = $adapter->getFileName('image-file');
				$fileExt = $this->getFileExtension($filepath);
				$filename = basename($filepath, $fileExt);
				$bannerDb->insert(array('image_url' => $filename . $fileExt));
				$this->redirect('/admin/banner/');
			}
			$this->view->errors = $errors;
		}
	}
	
	public function deleteAction(){
		$bannerId = $this->getParam('id');
		$bannerDb = new Application_Model_DbTable_Banner();
		$where = $bannerDb->getAdapter()->quoteInto('id = ?', $bannerId);
		
		$bannerDb->update( array('del_flag' => 1), $where);
		$this->redirect('/admin/banner');
	}
	public function getFileName($path, $ext) {
		return $bname = basename($path, $ext);
	}
	
	public function getFileExtension($path) {
		return $ext = strrchr($path, '.');
	}
	
}

